package com.dl.mall.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import org.junit.Test;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author DL
 * @create 2022-04-10 10:36
 */
@Component
public class AliyunOssUtils {

    // 阿里云API的内或外网域名
    private static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";

    // 阿里云API的密钥Access Key ID
    private static String accessKeyId = "LTAI5tPGuGfv5yB4deuBa2LK";

    // 阿里云API的密钥Access Key Secret
    private static String accessKeySecret = "3K1bKqfZoGFFWW6V5QMCF3pV6E49MY";

    // 阿里云API的bucket名称
    private static String bucketName = "mall-resource-bucket";

    // 赋值
    public static void settingIniOSS(String endpoint, String accessKeyId, String accessKeySecret,String bucketName) {
        AliyunOssUtils.endpoint = endpoint;
        AliyunOssUtils.accessKeyId = accessKeyId;
        AliyunOssUtils.accessKeySecret = accessKeySecret;
        AliyunOssUtils.bucketName = bucketName;
    }

    /**
     * 上传商品主图
     * @param prefix 路径前缀
     * @param productId 产品id作为图片名
     * @param multipartFile 文件
     * @return 文件名
     */
    public static String uploadFile(String prefix, String productId, MultipartFile multipartFile)
            throws OSSException, ClientException, FileNotFoundException {
        // 获取文件全名a.py
        String fullName = multipartFile.getOriginalFilename();
        // 获取文件的后缀名
        String suffix = fullName.substring(fullName.lastIndexOf("."));
        // 组成新的名称
        String fileName = productId + suffix;
        String objectName = prefix + fileName;
        // 创建OSSClient的实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            if(multipartFile.getSize() != 0 && !"".equals(multipartFile.getName())){
                // getInputStream()返回一个InputStream以从中读取文件的内容。通过此方法就可以获取到流
                InputStream multipartFileInputStream = multipartFile.getInputStream();
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, multipartFileInputStream);
                ossClient.putObject(putObjectRequest);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            // 关闭流
            ossClient.shutdown();
        }
        return objectName;
    }

    /**
     * 上传商品主图
     * @param prefix 路径前缀
     * @param files 多个文件
     * @return 文件名
     */
    public static String subImgUpload(String prefix, MultipartFile[] files) throws OSSException, ClientException, FileNotFoundException {
        StringBuffer stringBuffer = new StringBuffer();
        int i = 1;
        for (MultipartFile file : files) {
            // 获取文件全名a.py
            String fullName = file.getOriginalFilename();
            // 文件上传路径
            String suffix = fullName.substring(fullName.lastIndexOf("."));
            String fileName = "subImg_" +  i + suffix;

            stringBuffer.append(prefix).append(fileName).append(",");
            String objectName = prefix + fileName;

            // 创建OSSClient的实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            try {
                if(file.getSize() != 0 && !"".equals(file.getName())){
                    // getInputStream()返回一个InputStream以从中读取文件的内容。通过此方法就可以获取到流
                    InputStream multipartFileInputStream = file.getInputStream();
                    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, multipartFileInputStream);
                    ossClient.putObject(putObjectRequest);
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }finally {
                ossClient.shutdown();
            }
            i++;
        }
        stringBuffer.setLength(stringBuffer.length() - 1);
        return String.valueOf(stringBuffer);
    }

    /**
     * 上传商品主图
     * @param prefix 路径前缀
     * @param specsImgName 图片名
     * @param file 文件
     * @return 文件名
     */
    public static String specsImgUpload(String prefix, String specsImgName, MultipartFile file) throws OSSException, ClientException, FileNotFoundException {
        // 获取文件全名a.py
        String fullName = file.getOriginalFilename();
        // 文件上传路径
        String suffix = fullName.substring(fullName.lastIndexOf("."));
        String fileName = specsImgName + suffix;

        String objectName = prefix + fileName;

        // 创建OSSClient的实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            if(file.getSize() != 0 && !"".equals(file.getName())){
                // getInputStream()返回一个InputStream以从中读取文件的内容。通过此方法就可以获取到流
                InputStream multipartFileInputStream = file.getInputStream();
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, multipartFileInputStream);
                ossClient.putObject(putObjectRequest);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            ossClient.shutdown();
        }
        return objectName;
    }


    @Test
    public void testAli(){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tPGuGfv5yB4deuBa2LK";
        String accessKeySecret = "3K1bKqfZoGFFWW6V5QMCF3pV6E49MY";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "mall-resource-bucket";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "test/X70.png";
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
        String filePath= "C:\\Users\\123\\OneDrive\\桌面\\图片\\头像\\1.jpg";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
